/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.gbvbahia.vendas.controllers.servlet;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet genérico para enviar arquivos ao usuário.<br> Utilizar
 * br.com.gbvbahia.manager.util.JsfUtil.downloadFile para enviar
 * arquivos.
 *
 * Utilizar PrimeFaces Download
 * @author Guilherme Braga
 * @since 2013/03/07
 */
@WebServlet(name = "ServletFileDownload", urlPatterns = { "/SFile" })
public class ServletFileDownload extends HttpServlet {

    /**
     * Tamanho do buffer para escrita do arquivo para download.
     */
    private static final int BUFFER = 1024;

    /**
     * Processa requisição HTTP para métoso:
     * <code>GET</code> e
     * <code>POST</code>.<br> Parâmetros trabalhados:<br> caminhoArquivo =
     * Caminho totalmente qualificado para o arquivo a ser enviado ao
     * usuário.<br> nomeArquivo = Nome do arquivo a ser exibido na janela do
     * download.<br> O método:
     * br.com.gbvbahia.manager.util.JsfUtil.downloadFile torna a
     * utilização deste servlet transparente.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        //caminhoArquivo: caminho completo do arquivo, desde a raiz
        File arquivo = new File(request.getParameter("caminhoArquivo"));
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename="
                + request.getParameter("nomeArquivo"));
        InputStream in = new FileInputStream(arquivo);
        ServletOutputStream output = response.getOutputStream();
        int bit = BUFFER;
        try {
            while (bit >= 0) {
                bit = in.read();
                if (bit >= 0) {
                    output.write(bit);
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        } finally {
            output.flush();
            output.close();
            in.close();
        }
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Servlet de download de arquivos para usuários.";
    }
}
